from flask import Flask, session, redirect, url_for, escape, request, render_template, flash

import _login, _email, _report, _record, _cmd

import threading
from queue import Queue
from time import sleep, time


flag_run = True
app = Flask(__name__)

@app.route('/')
def index():
    if 'username' in session:
        return render_template('index.html', username=escape(session['username']))
    else:
        return render_template('index.html')

@app.route('/login', methods=['POST', 'GET'])
def login():
    if request.method == 'POST':
        try:
            w3name = request.form['w3name']
            w3pwd = request.form['w3pwd']
        except Exception as e:
            app.logger.error('%s' % e)

        if _login.login_w3(w3name, w3pwd):
            session['username'] = w3name
            session['password'] = w3pwd
            return render_template('index.html', username=w3name)
        else:
            flash('w3name or w3pwd wrong!')
            return redirect(url_for('index'))

    flash('invalid operation!')
    return redirect(url_for('index'))

@app.route('/logout', methods=['POST', 'GET'])
def logout():
    if not 'username' in session:
        flash('Not login yet!')
        return redirect(url_for('index'))

    session.pop('username', None)
    session.pop('password', None)
    return redirect(url_for('index'))

@app.route('/suggest', methods=['POST', 'GET'])
def suggest():
    if not 'username' in session:
        flash('Not login yet!')
        return redirect(url_for('index'))

    if request.method == 'POST':
        try:
            value_suggest = request.form['suggest']
        except Exception as e:
            app.logger.error('%s' % e)
            flash('get suggest fail!')
            return redirect(url_for('index'))
        
        _email.send("wuhan.liuyuan@huawei.com", value_suggest)
        # return render_template('index.html', error = 'Thanks! We received!', username=escape(session['username']))
        return '%s\r\nThanks! We received!' % value_suggest

    flash('invalid operation!')
    return redirect(url_for('index'))

class ObjReport:
   def __init__(self, timestamp, w3name, version):
        self.timestamp = timestamp
        self.w3name = w3name
        self.version = version
      
@app.route('/get_report', methods=['POST', 'GET'])
def get_report():
    if not 'username' in session:
        flash('Not login yet!')
        return redirect(url_for('index'))

    if request.method == 'POST':
        try:
            value_version = request.form['version']
        except Exception as e:
            app.logger.error('%s' % e)
            flash('get version fail!')
            return redirect(url_for('index'))
        
        timestamp = int(time())
        username = escape(session['username'])
        _record.open(timestamp, username, _cmd.CMD_APR_REPORT)
        q_report.put(ObjReport(timestamp, username, value_version))
        
        # flash('Just waiting email...')
        return 'Just waiting email...'

    flash('invalid operation!')
    return redirect(url_for('index'))
    
if __name__ == '__main__':
    _record.init(app)
    
    # 各模块
    threads = []
    q_report = Queue(maxsize=100)
    
    for i in range(0, 3):
        t = threading.Thread(target=_report.get_report, args=(app,q_report,))
        threads.append(t)

    count = range(len(threads))
    for i in count:
        threads[i].start()

    # Web
    app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'
    
    app.run(
        host='127.0.0.1',
        port= 5000,
        debug=True,
        threaded=True
    )
    
    # 收工
    flag_run = False
    for i in count:
        threads[i].join()
    _record.finish()
    